package 网络编程.综合练习.上传文件;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.UUID;

public class MyRun implements Runnable{
    //创建构造方法接收Socket对象
    Socket socket;
    public MyRun(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        try {
            //3.从连接通道获取输入流
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());

            //4.创建本地接收文件的对象
            String name = UUID.randomUUID().toString().replace("-","");
            FileOutputStream fos=new FileOutputStream("F\\aaa\\"+name+".jpg");

            //5.接收文件,并写入服务器端的本地
            byte[] bytes=new byte[1024];
            int len;
            while ((len=bis.read(bytes))!=-1){
                fos.write(bytes,0,len);
            }

            //6.接收完文件,反馈信息给客户端
            OutputStream os = socket.getOutputStream();
            String data="文件,已经收到了";
            os.write(data.getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
